'use strict';
const path = require("path")
const pkgDir = require('pkg-dir').sync
const fse = require('fs-extra');
const { isObject } = require("@wss-cli-dev/utils")
const formatPath = require('@wss-cli-dev/format-path');
const { getNpmLatestVersion, getDefaultRegistry } = require('@wss-cli-dev/get-npm-info');
const npminstall = require("npminstall")
const pathExists = require("path-exists").sync
// import pathExists from "path-exists"
class Packages {
  constructor(options) {
    if (!options || !isObject(options)) {
      throw new Error("options 不能为空")
    }
    // 传入路径
    this.targetPath = options.targetPath
    // 缓存路径=>存储路径
    this.storeDir = options.storeDir
    // name
    this.packageName = options.packageName
    this.packageVersion = options.packageVersion
    this.cacheFilePathPrefix = this.packageName.replace('/', '_');
  }
  async prepare() {
    // 判断缓存路径是否存在   当前是否最新版本
    if (this.storeDir && !pathExists(this.storeDir)) {
      fse.mkdirpSync(this.storeDir)
    }
    if (this.packageVersion === "latest") {
      // TODO 当前有问题等发布版本号后再使用 先固定版本
      console.log(await getNpmLatestVersion(this.packageName));
      // await getNpmLatestVersion(this.packageName)
      // this.packageVersion = "1.0.1"
    }
  }
  get cacheFilePath() {
    return path.resolve(this.storeDir, `.store/${this.cacheFilePathPrefix}@${this.packageVersion}`);
  }
  getSpecificCacheFilePath(packageVersion) {
    return path.resolve(this.storeDir, `.store/${this.cacheFilePathPrefix}`);
  }
  // 判断是否存在该文件
  async exists() {
    if (this.storeDir) {
      // console.log(this.cachesFilePath);
      await this.prepare()
      // 当前路径存在执行更新 不存在执行安装
      return pathExists(this.cacheFilePath)
    } else {
      return pathExists(this.targetPath)
    }
  }
  // 安装
  async install() {
    await this.prepare()
    npminstall({
      root: this.targetPath,
      storeDir: this.storeDir,
      registry: "https://registry.npmjs.org/",
      pkgs: [
        {
          // name: this.packageName,
          name: this.packageName,
          version: this.packageVersion
        }
      ]
    })
  }
  // 更新
  async update() {
    await this.prepare()
    // 1. 最新版本号
    // TODO await getNpmLatestVersion(this.packageName)
    const newLatestVersion = this.packageVersion
    // 2. 生成最新版本号的文件路径
    const latestFilePath = this.getSpecificCacheFilePath(newLatestVersion)
    // 3. 如果不存在 怎直接安装 最新版本
    if (!pathExists(latestFilePath)) {
      // 执行安装install
      npminstall({
        root: this.targetPath,
        storeDir: this.storeDir,
        registry: "https://registry.npmjs.org/", // todo huomianhuan
        pkgs: [
          {
            // name: this.packageName,
            name: this.packageName,
            version: this.packageVersion
          }
        ]
      })
      this.packageVersion = newLatestVersion;
    } else {
      this.packageVersion = newLatestVersion;
    }
  }
  // 获取文件入口路径
  getRootFilePath() {
    function _getRootFile(targetPath) {
      // 获取所在目录
      const dir = pkgDir(targetPath)
      if (dir) {
        // 读取
        const pathFile = require(path.resolve(dir, "package.json"))
        // 寻找
        if (pathFile && pathFile.main) {
          // 兼容
          return formatPath(path.resolve(dir, pathFile.main))
        }
      }
      return null
    }
    if (this.storeDir) {
      // console.log();
      return _getRootFile(this.cachesFilePath)

    } else {
      return _getRootFile(this.targetPath)
    }
  }
}
module.exports = Packages;